package com.jh.paymentchannel.msdf.common;

import com.jh.paymentchannel.msdf.algorithm.PrivateKeyReader;
import com.jh.paymentchannel.msdf.algorithm.PublicKeyReader;

import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 
 * Description:
 * Generate a 2048-bit RSA private key
 * $$ openssl genrsa -out private_key.pem 2048
 * Convert private Key to PKCS#8 format (so Java can read it)
 * $$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out msdf_private_key.der -nocrypt
 * Output public key portion in DER format (so Java can read it)
 * $$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
 * 
 * @author Luke
 *
 */
public class CertServiceSingleton {
	private static CertServiceSingleton instance = null;
	
	private PrivateKey myPrivateKey = null;
	private PublicKey theirPublicKey = null;

	// 屏蔽外部创建对象
	private CertServiceSingleton(String myPrivateKeyPath, String theirPublicKeyPath) {
		try {
			myPrivateKey = PrivateKeyReader.get(myPrivateKeyPath);
			theirPublicKey = PublicKeyReader.get(theirPublicKeyPath);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public static void initCertPath(String myPrivateKeyPath, String theirPublicKeyPath) {
		if (instance != null) {
			try {
				instance = null;
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		if(!new File(myPrivateKeyPath).isAbsolute()) {
			myPrivateKeyPath = CertServiceSingleton.class.getClassLoader().getResource(myPrivateKeyPath).getPath();
		}
		if(!new File(theirPublicKeyPath).isAbsolute()) {
			theirPublicKeyPath = CertServiceSingleton.class.getClassLoader().getResource(theirPublicKeyPath).getPath();
		}
		
		instance = new CertServiceSingleton(myPrivateKeyPath, theirPublicKeyPath);
	}

	public static PrivateKey getPrivateKey() {
	    return instance != null ? instance.myPrivateKey : null;
	}
	
	public static PublicKey getPubliceKey() {
	    return instance != null ? instance.theirPublicKey : null;
	}

}
